package com.xingda.packing.service;


import com.google.common.base.Stopwatch;
import com.xingda.packing.domain.PackProductionLine;
import com.xingda.packing.enums.EventType;
import com.xingda.packing.task.generate.TaskGenerateService;
import com.xingda.packing.task.handle.TaskHandleService;
import com.xingda.packing.task.listener.TaskListenerService;
import com.xingda.packing.task.ticket.AbstractTaskTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TaskManagerService2 extends Thread {

    @Resource
    private PackProductionLine packProductionLine;
    @Resource
    private List<TaskGenerateService> taskGenerateList;
    @Resource
    private List<TaskHandleService> taskHandleList;
    @Resource
    private List<TaskListenerService> taskListenerList;

    @Override
    public void run() {
        while (true) {
            Stopwatch stopwatch = Stopwatch.createStarted();
            try {
                if (packProductionLine.initRunning(2)) {
                    for (TaskGenerateService generateService : taskGenerateList) {
                        AbstractTaskTicket taskTicket = generateService.generate(packProductionLine, 2);
                        if (Objects.nonNull(taskTicket)) {
                            if (packProductionLine.getRobot().checkCanAssignTaskTicket(2)) {
                                packProductionLine.getRobot().assignTaskTicket(taskTicket, 2);
                            }
                            break;
                        }
                    }
                }
                taskHandleList.stream().filter(handle -> handle.accept(packProductionLine, 2))
                        .forEach(handle -> handle.process(packProductionLine, 2));
                taskListenerList.stream().filter(listener -> listener.accept(packProductionLine, 2))
                        .forEach(listener -> listener.monitor(packProductionLine, 2));
                //程序调度中的报警
                packProductionLine.triggerAlarm(2);
                stopwatch.stop();
                log.info("执行TaskManagerService2共耗时：{}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
//                暂停线程1秒，防止run频繁执行
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (Exception ex) {
                log.error("错误", ex);
                packProductionLine.getEventCreater().createPkEvent(EventType.ALARM, 2, ex.getMessage());
            }
        }
    }
}
